package tech.abing.spider.task.pageprocessor.amac;

import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import tech.abing.spider.component.PageProcessor;
import tech.abing.spider.component.PageScript;
import tech.abing.spider.model.Proccessable;
import tech.abing.spider.page.OkPage;
import tech.abing.spider.page.Page;
import tech.abing.spider.request.BasicRequest;
import tech.abing.spider.request.StartContext;
import tech.abing.spider.task.model.amac.CurriculumVitaeEntity;
import tech.abing.spider.task.model.amac.ExecutivesEntity;
import tech.abing.spider.task.model.amac.FundManagerEntity;
import tech.abing.spider.util.DateUtils;
import tech.abing.spider.util.StringUtils;
import tech.abing.spider.util.UuIdPublic;

public class ManagerDetailProcessor implements PageProcessor {

	private static final String BASE_URL = "http://gs.amac.org.cn/amac-infodisc/res/pof/manager/";
	
	private static Logger logger = Logger.getLogger(ManagerDetailProcessor.class);
	
	private static AtomicInteger atomicInteger = new AtomicInteger(0);
	
	static Pattern normalContain = Pattern.compile("私募基金管理人");//正常页面必定会存在的字符，你也可以使用页面上其他的字符
	
	@Override
	public PageScript getJavaScript() {
		return null;
	}

	@Override
	public Pattern getNormalContain() {
		return normalContain;
	}

	@Override
	public void process(OkPage page, StartContext context, List<BasicRequest> queue,
			List<Proccessable> objectContainer) throws Exception {
		Document doc = Jsoup.parse(page.getContent());
		//logger.info(page.getContent());
		JSONObject ctxObj = (JSONObject)page.getRequest().getExtParams().get("ctxObj");
		//System.out.println(ctxObj.toString());
		FundManagerEntity manager = new FundManagerEntity();
		manager.setCreateTime(new Timestamp(System.currentTimeMillis()));
		Element ele = doc.select("table[class=\"table table-center table-info\"] > tbody").first();
		manager.setManagerName(ele.select("#complaint1").text());
		if (ele.select("#complaint1").text().equals("深圳市翼虎投资管理有限公司")) {
			System.out.println(ele.select("credit-info").text());
		}
//		manager.setHonestyInfo(ele.select("#specialTips").text());
		manager.setHonestyInfo(ele.select("table[class=\"table table-center table-info\"]").text());
		manager.setManagerName(ele.select("#complaint1").text());
		if(ele.getElementsMatchingOwnText("基金管理人全称\\(英文\\)").size()>0){
			manager.setManagerEnglishName(ele.getElementsMatchingOwnText("基金管理人全称\\(英文\\)").first().nextElementSibling().text());
		}
		manager.setRegistrationNo(ele.getElementsMatchingOwnText("登记编号:").first().nextElementSibling().text());
		String orgCode = ele.getElementsMatchingOwnText("组织机构代码:").first().nextElementSibling().text();
		manager.setOrgCode(orgCode);
		String registerDate = ele.getElementsMatchingOwnText("登记时间:").first().nextElementSibling().text();//注册日期
		if(StringUtils.isNotEmpty(registerDate)){
			manager.setRegisterDate(DateUtils.parseDate(registerDate));
		}
		String establishDate = ele.getElementsMatchingOwnText("成立时间:").first().nextElementSibling().text();//成立日期
		if(StringUtils.isNotEmpty(establishDate)){
			manager.setEstablishDate(DateUtils.parseDate(establishDate));
		}
		manager.setRegisterAddress(ele.getElementsMatchingOwnText("注册地址:").first().nextElementSibling().text());//注册地址
		manager.setOfficeAddress(ele.getElementsMatchingOwnText("办公地址:").first().nextElementSibling().text());//办公地址
		if(ele.getElementsMatchingOwnText("注册资本\\(万元\\)\\(人民币\\)").size()>0){
			manager.setRegisteredCapital(Double.valueOf(ele.getElementsMatchingOwnText("注册资本\\(万元\\)\\(人民币\\)").first().nextElementSibling().text().replace(",", "")));//注册资本(万元)
		}
		if(ele.getElementsMatchingOwnText("实缴资本\\(万元\\)\\(人民币\\)").size()>0){
			String paidinCapital = ele.getElementsMatchingOwnText("实缴资本\\(万元\\)\\(人民币\\)").first().nextElementSibling().text();
			if(StringUtils.isNotEmpty(paidinCapital)){
				manager.setPaidinCapital(Double.valueOf(ele.getElementsMatchingOwnText("实缴资本\\(万元\\)\\(人民币\\)").first().nextElementSibling().text().replace(",", "")));//实缴资本(万元)
			}
		}
		manager.setEnterpriseType(ele.getElementsMatchingOwnText("企业性质:").first().nextElementSibling().text());//企业性质
		manager.setPaidinProportion(ele.getElementsMatchingOwnText("注册资本实缴比例:").first().nextElementSibling().text());//注册资本实缴比例
		manager.setPrimaryInvesttype(ele.getElementsMatchingOwnText("管理基金主要类别:").first().nextElementSibling().text());//管理基金主要类别
		manager.setOtherBusinessType(ele.getElementsMatchingOwnText("业务类型:").first().nextElementSibling().text());//申请的其他业务类型
		manager.setStaffNumber(Integer.valueOf(ele.getElementsMatchingOwnText("员工人数:").first().nextElementSibling().text().replace(",", "")));//员工人数
		manager.setOrgUrl(ele.getElementsMatchingOwnText("机构网址:").first().nextElementSibling().text());//机构网址
		manager.setLegalOpinionState(ele.getElementsMatchingOwnText("法律意见书状态:").first().nextElementSibling().text());//法律意见书状态
		if(ele.getElementsMatchingOwnText("律师事务所名称:").size()>0){
			manager.setLawFirm(ele.getElementsMatchingOwnText("律师事务所名称:").first().nextElementSibling().text());//律师事务所名称
		}
		if(ele.getElementsMatchingOwnText("律师姓名:").size()>0){
			manager.setLawyer(ele.getElementsMatchingOwnText("律师姓名:").first().nextElementSibling().text());//律师名称
		}
		manager.setArtificialPersonName(ele.getElementsMatchingOwnText("法定代表人/执行事务合伙人\\(委派代表\\)姓名:").first().nextElementSibling().text());//法定代表人/执行事务合伙人(委派代表)姓名
		manager.setHasQualification(ele.getElementsMatchingOwnText("是否有从业资格:").first().nextElementSibling().text());//是否有从业资格
		manager.setWayOfQualification(ele.getElementsMatchingOwnText("资格取得方式:").first().nextElementSibling().text());//资格取得方式
		String lastUpdateTime =  ele.getElementsMatchingOwnText("机构信息最后更新时间:").first().nextElementSibling().text();
		if(StringUtils.isNotEmpty(lastUpdateTime)){
			manager.setLastUpdateTime(DateUtils.parseDate(lastUpdateTime));
		}
		manager.setSpecialNotice(ele.select("#specialInfos").text());
		if(ele.getElementsMatchingOwnText("是否为会员:").size()>0){
			manager.setIsVip(ele.getElementsMatchingOwnText("是否为会员:").first().nextElementSibling().text());
		}
		if(ele.getElementsMatchingOwnText("当前会员类型:").size()>0){
			manager.setVipType(ele.getElementsMatchingOwnText("当前会员类型:").first().nextElementSibling().text());
		}
		if(ele.getElementsMatchingOwnText("入会时间:").size()>0){
			manager.setInitiationTime(DateUtils.parseDate(ele.getElementsMatchingOwnText("入会时间:").first().nextElementSibling().text()));
		}
		
		manager.setFundScale(Double.valueOf(ctxObj.getDouble("fundScale")));
		manager.setHasCredittips(ctxObj.getString("hasCreditTips"));
		manager.setHasSpecialtips(ctxObj.getString("hasSpecialTips"));
		manager.setRegAdrAgg(ctxObj.getString("regAdrAgg"));
		manager.setRegisterCity(ctxObj.getString("registerCity"));
		manager.setRegisterProvince(ctxObj.getString("registerProvince"));
		manager.setUrl(BASE_URL.concat(ctxObj.getString("url")));
		manager.setFundCount(ctxObj.getInt("fundCount"));
		manager.setInBlacklist(ctxObj.getString("inBlacklist"));
		manager.setManagerHasproduct(ctxObj.getString("managerHasProduct"));
		manager.setOfficeCity(ctxObj.getString("officeCity"));
		manager.setOfficeCoordinate(ctxObj.getString("officeCoordinate"));
		manager.setOfficeProvince(ctxObj.getString("officeProvince"));
		manager.setRegCoordinate(ctxObj.getString("regCoordinate"));
		
		//以下是提取履历表的信息
		//Element cvTable = ele.select("tr:nth-child(19) > td.td-content > table.table.table-center.table-noborder > tbody").first();
		Element cvTable = ele.select("td.td-title:containsOwn(法定代表人/执行事务合伙人(委派代表)工作履历:)").first().nextElementSibling().getElementsByTag("tbody").first();
		boolean hasCv = true;
		if(cvTable != null){
			Elements cvTrs = cvTable.children();
			if(cvTrs!=null && !cvTrs.isEmpty()){
				for (Element element : cvTrs) {//迭代每一行
					CurriculumVitaeEntity cvEntity = new CurriculumVitaeEntity();
					cvEntity.setId(UuIdPublic.timeStrongID(5));
					cvEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
					cvEntity.setOrgCode(orgCode);
					cvEntity.setServedTime(element.select("td").get(0).text());
					cvEntity.setServiceUnit(element.select("td").get(1).text());
					cvEntity.setDuties(element.select("td").get(2).text());
					cvEntity.setManagerUrl(BASE_URL.concat(ctxObj.getString("url")));
					StringUtils.removeSpace(cvEntity);
					objectContainer.add(cvEntity);
				}
			}else{
				hasCv = false;
			}
		}
		
		//以下是提取【高管情况】表的信息：
		//Element excutivesTable = ele.select("tr:nth-child(20) > td.td-content > table.table.table-center.table-noborder > tbody").first();
		Element excutivesTable = ele.select("td.td-title:containsOwn(高管情况:)").first().nextElementSibling().getElementsByTag("tbody").first();
		if(excutivesTable != null){
			Elements excutivesTrs = excutivesTable.children();
			if(excutivesTrs!=null && !excutivesTrs.isEmpty()){
				for (Element element : excutivesTrs) {
					ExecutivesEntity exEntity = new ExecutivesEntity();
					exEntity.setId(UuIdPublic.timeStrongID(5));
					exEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
					exEntity.setOrgCode(orgCode);
					exEntity.setExecutivesName(element.select("td").get(0).text());
					exEntity.setPosition(element.select("td").get(1).text());
					exEntity.setHasQualification(element.select("td").get(2).text());
					exEntity.setManagerUrl(BASE_URL.concat(ctxObj.getString("url")));
					exEntity.setId(UuIdPublic.timeStrongID(5));
					StringUtils.removeSpace(exEntity);
					objectContainer.add(exEntity);
				}
			}
		}
		

		//暂行办法实施前成立的基金：(存放的是每个基金的id，以逗号隔开)
		//Element beforeFund = ele.select("tr:nth-child(22) > td.td-content").first();
		Element beforeFund = ele.select("td.td-title:containsOwn(暂行办法实施前成立的基金:)").first().nextElementSibling();
		Elements beforeFundLink = beforeFund.select("a[href]");
		StringBuffer beforeFunds = new StringBuffer();
		int actualFundCount = 0;
		for (Element element : beforeFundLink) {
			String strs[] = element.attr("href").split("/");
			beforeFunds.append(strs[strs.length-1].replace(".html", "")+",");
			actualFundCount++;
		}
		//暂行办法实施后成立的基金：(存放的是每个基金的id，以逗号隔开)
		//Element afterFund = ele.select("tr:nth-child(23) > td.td-content").first();
		Element afterFund = ele.select("td.td-title:containsOwn(暂行办法实施后成立的基金:)").first().nextElementSibling();
		Elements afterFundLink = afterFund.select("a[href]");
		StringBuffer afterFunds = new StringBuffer();
		for (Element element : afterFundLink) {
			String strs[] = element.attr("href").split("/");
			afterFunds.append(strs[strs.length-1].replace(".html", "")+",");
			actualFundCount++;
		}
		manager.setBeforeFunds(beforeFunds.toString());
//		manager.setAfterFunds(afterFunds.toString());
		manager.setActualFundCount(actualFundCount);
		manager.setId(UuIdPublic.timeStrongID(5));
		StringUtils.removeSpace(manager);
		objectContainer.add(manager);
		int count = atomicInteger.incrementAndGet();
		String pageIndex = (String)page.getRequest().getExtParams().get("pageIndex");
		String cvResult = "";
		if(!hasCv){
			cvResult = ",当前机构无高管履历!";
		}
		logger.info("当前第"+pageIndex+"页,解析第"+count+"条数据完成,当前机构:{"+manager.getOrgCode()+":"+manager.getManagerName()+"}"+cvResult);
		
		
	}

	@Override
	public void processErrorPage(Page page, StartContext context,List<Proccessable> objectContainer) throws Exception {

	}

}
